package com.ulic.customerManApplication.journeylovemodule.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.ulic.customerManApplication.membermodule.bo.Member;
import com.ulic.customerManApplication.base.BaseAction;
import com.ulic.customerManApplication.commonmodule.bo.Organization;
import com.ulic.customerManApplication.commonmodule.service.OrganizationService;
import com.ulic.customerManApplication.commonmodule.vo.ImpDataInfor;
import com.ulic.customerManApplication.constant.CONSTANT;
import com.ulic.customerManApplication.journeylovemodule.bo.JourneyOfLoveActivity;
import com.ulic.customerManApplication.journeylovemodule.service.JourneyLoveService;
import com.ulic.customerManApplication.journeylovemodule.vo.JourneyLoveVO;
import com.ulic.customerManApplication.membermodule.bo.SubMember;
import com.ulic.customerManApplication.membermodule.service.MemberService;
import com.ulic.customerManApplication.membermodule.service.SubMemberService;
import com.ulic.customerManApplication.pager.PagerModel;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.util.config.ConfigInfo;
import com.ulic.customerManApplication.util.excel.DownloadDemo;
import com.ulic.customerManApplication.util.excel.DownloadExcel;
import com.ulic.customerManApplication.util.excel.ExpJourneyLoves;
import com.ulic.customerManApplication.util.excel.UploadFile;
@Component("journeyLoveAction")
@Scope("prototype")
public class JourneyLoveAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JourneyLoveService journeyLoveService;
	private JourneyOfLoveActivity journeyLove;
	private File journeyLovesFile;
	private String fileName;
	private String impDataInfor;
	private OrganizationService organizationService ;
	private String subCityHidden;
    private MemberService memberService;
    private SubMemberService subMemberService;
	public String getSubCityHidden() {
		return subCityHidden;
	}
	public void setSubCityHidden(String subCityHidden) {
		this.subCityHidden = subCityHidden;
	}
	public File getJourneyLovesFile() {
		return journeyLovesFile;
	}
	public void setJourneyLovesFile(File journeyLovesFile) {
		this.journeyLovesFile = journeyLovesFile;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getImpDataInfor() {
		return impDataInfor;
	}
	public void setImpDataInfor(String impDataInfor) {
		this.impDataInfor = impDataInfor;
	}
	public JourneyOfLoveActivity getJourneyLove() {
		return journeyLove;
	}
	public void setJourneyLove(JourneyOfLoveActivity journeyLove) {
		this.journeyLove = journeyLove;
	}
	public JourneyLoveService getJourneyLoveService() {
		return journeyLoveService;
	}
	
	@Resource
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	@Resource
	public void setJourneyLoveService(JourneyLoveService journeyLoveService) {
		this.journeyLoveService = journeyLoveService;
	}
   
	
	
	
	public MemberService getMemberService() {
		return memberService;
	}
	@Resource
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	public SubMemberService getSubMemberService() {
		return subMemberService;
	}
	@Resource
	public void setSubMemberService(SubMemberService subMemberService) {
		this.subMemberService = subMemberService;
	}
	@Override
	public String execute() throws Exception {
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		PagerModel pm = journeyLoveService.getJourneyLoves(curPage);
		httpServletRequest.setAttribute("pm",pm);
		return SUCCESS;
	}
	
	public String searchJourneyLoves(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		String buttonName = httpServletRequest.getParameter("buttonType");
		if(!"exp".equals(buttonName)){
		String startDate = httpServletRequest.getParameter("startDate");
		String endDate = httpServletRequest.getParameter("endDate");
		String roleName = (String)session.get("rolename");
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		JourneyLoveVO journeyLoveVO = new JourneyLoveVO();
		journeyLoveVO.setStartDate(startDate);
		journeyLoveVO.setEndDate(endDate);
		journeyLoveVO.setRoleName(roleName);
		journeyLoveVO.setUser(user);
		if(journeyLove==null){
			journeyLove = new JourneyOfLoveActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 journeyLove.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 journeyLove.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 journeyLove.setSubCity(organ.getUm_organ_id());
			 }
		} 
		journeyLoveVO.setJourneyOfLoveActivity(journeyLove);
		PagerModel pm = journeyLoveService.getJourneyLoves(journeyLoveVO,curPage);
		JourneyOfLoveActivity jLoveActivity = null;
		if(pm.getTotal()!=0){
			//统计爱心之旅各类会员数量
			List<Object> datas = pm.getDatas();
			List<Object> journeyList = new ArrayList<Object>();
			for(Object data : datas){
				if(data instanceof JourneyOfLoveActivity){
					jLoveActivity = (JourneyOfLoveActivity)data;
					Map<String,Long> map = subMemberService.getMemberCountByJourId(jLoveActivity.getId(), "");
					jLoveActivity.setGreenCardMember(map.containsKey("绿卡会员") ? map.get("绿卡会员").intValue() : 0);//绿卡
					jLoveActivity.setSilverCardMember(map.containsKey("银卡会员") ? map.get("银卡会员").intValue() : 0);//银卡
					jLoveActivity.setGoldenCardMember(map.containsKey("金卡会员") ? map.get("金卡会员").intValue() : 0);//金卡
					jLoveActivity.setPlatinumCardMember(map.containsKey("金箔卡会员") ? map.get("金箔卡会员").intValue() : 0);//铂金卡
					jLoveActivity.setDiamondCardMember(map.containsKey("钻石卡会员") ? map.get("钻石卡会员").intValue() : 0);//钻石卡
					journeyList.add(jLoveActivity);
				}
			}
			pm.setDatas(journeyList);
			for(Object obj:journeyLoveService.getJourneyLoves(journeyLoveVO,1,pm.getTotal()).getDatas()){
				if(obj instanceof JourneyOfLoveActivity){
					jLoveActivity = (JourneyOfLoveActivity)obj;
					if(jLoveActivity.getActivityFee()!=null){
						journeyLoveVO.setTotalActFee(journeyLoveVO.getTotalActFee()+jLoveActivity.getActivityFee());
					}
					if(jLoveActivity.getDiamondCardMember()!=null){
						journeyLoveVO.setTotalDiamMem(journeyLoveVO.getTotalDiamMem()+jLoveActivity.getDiamondCardMember());
					}
					if(jLoveActivity.getDonateMoney()!=null){
						journeyLoveVO.setTotalDonateMon(journeyLoveVO.getTotalDonateMon()+jLoveActivity.getDonateMoney());
					}
					if(jLoveActivity.getDonateStuNum()!=null){
						journeyLoveVO.setTotalDonateStu(journeyLoveVO.getTotalDonateStu()+jLoveActivity.getDonateStuNum());
					}
					if(jLoveActivity.getGoldenCardMember()!=null){
						journeyLoveVO.setTotalGoldMem(journeyLoveVO.getTotalGoldMem()+jLoveActivity.getGoldenCardMember());
					}
					if(jLoveActivity.getGreenCardMember()!=null){
						journeyLoveVO.setTotalGreenMem(journeyLoveVO.getTotalGreenMem()+jLoveActivity.getGreenCardMember());
					}
					if(jLoveActivity.getPlatinumCardMember()!=null){
						journeyLoveVO.setTotalPlanMem(journeyLoveVO.getTotalPlanMem()+jLoveActivity.getPlatinumCardMember());
					}
					if(jLoveActivity.getSelfDrivings()!=null){
						journeyLoveVO.setTotalselfDri(journeyLoveVO.getTotalselfDri()+jLoveActivity.getSelfDrivings());
					}
					if(jLoveActivity.getSilverCardMember()!=null){
						journeyLoveVO.setTotalSilMem(journeyLoveVO.getTotalSilMem()+jLoveActivity.getSilverCardMember());
					}
					
				}
			}
		}
		httpServletRequest.setAttribute("pm",pm);
		httpServletRequest.setAttribute("startDate", startDate);
		httpServletRequest.setAttribute("endDate", endDate);
		httpServletRequest.setAttribute("roleName",roleName);
		httpServletRequest.setAttribute("journeyLoveVO", journeyLoveVO);
		return SUCCESS;
		}else{
			return expJourneyLoves();
		}
	}
	
	public String toSaveJourneyLove()throws Exception{
		String roleName = (String)session.get("rolename");
		if(journeyLove==null){
			journeyLove = new JourneyOfLoveActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 journeyLove.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 journeyLove.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 journeyLove.setSubCity(organ.getUm_organ_id());
			 }
		} 
		return SUCCESS;
	}
	
	
	public String saveJourneyLove()throws Exception{
		journeyLove.setCreateDate(new Date());
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		journeyLove.setUser(user);
		journeyLove.setDonateStuNum(0);//让其初始数据为0，然后根据添加的会员数量自动更新
		journeyLove.setGreenCardMember(0);
		journeyLove.setSilverCardMember(0);
		journeyLove.setGoldenCardMember(0);
		journeyLove.setPlatinumCardMember(0);
		journeyLove.setDiamondCardMember(0);
		if(journeyLove.getActivityFee()==null){
			 journeyLove.setActivityFee(0.00);
		 }
		journeyLoveService.addJourneyLove(journeyLove);
		return SUCCESS;
	}
	public String viewJourneyLove()throws Exception{
		journeyLove = journeyLoveService.getJourneyLoveById(journeyLove.getId());
		return SUCCESS;
	}
	public String updateJourneyLove()throws Exception{
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		journeyLove = journeyLoveService.getJourneyLoveById(journeyLove.getId());
		String roleName = (String)session.get("rolename");
		if(!"THIRDADMIN".equals(roleName)){
			httpServletRequest.setAttribute("expensedCityList", organizationService.findOrganizationByParentId(journeyLove.getSubCompany()));
		}
		return SUCCESS;
	}
	public String updatedJourneyLove()throws Exception{
		 User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		 journeyLove.setUser(user);
		 if(journeyLove.getActivityFee()==null){
			 journeyLove.setActivityFee(0.00);
		 }
		 journeyLoveService.modifyJourneyLove(journeyLove);
		 return SUCCESS;
	}
	public String deleteJourneyLove()throws Exception{
		journeyLove = journeyLoveService.getJourneyLoveById(journeyLove.getId());
		Set<SubMember> subMembers = journeyLove.getSubMembers();
		Member member = null;
		for(SubMember subMember:subMembers){
			if(subMember.getSub_idCard()!=null && subMember.getSub_idCard().length()!=0){
				member = memberService.getMember(1,subMember.getSub_idCard());
			}else if(subMember.getSub_cellPhone()!=null && subMember.getSub_cellPhone().length()!=0){
				member = memberService.getMember(2,subMember.getSub_cellPhone());
			}else{
				member = null;
			}
			if(member!=null){
				member.setDonateStuNum(member.getDonateStuNum()-subMember.getSub_donateStuNum());
				member.setMemberType(getMemberType(member.getDonateStuNum()));
				if(member.getDonateStuNum()<0){
					member.setDonateStuNum(0);
				}
				memberService.modifyMember(member);
			
				/*SubMember smm = null;
				for(SubMember sMember:subMemberService.getSubMembers(subMember.getSub_idCard())){
					if(sMember instanceof SubMember){
						smm = (SubMember)sMember;
						smm.setSub_memberType(member.getMemberType());
						subMemberService.modifySubMember(smm);
					}
				}*/
			}
		}
		journeyLoveService.removeJourneyLove(journeyLove);
		return SUCCESS;
	}
	
   public String impJourneyLoves() throws Exception{
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		long date = new Date().getTime();
		ImpDataInfor impDataInfor = new ImpDataInfor();
		List<Integer> errorNumbers = new ArrayList<Integer>();
		String realPath = ConfigInfo.getPropertiesValue("uploadfile.path");
		String rolename = session.get("rolename").toString();
		if(fileName != null && fileName.length() !=0){
			fileName = UploadFile.upload(journeyLovesFile, fileName,date);//先将文件上传到服务器
			File f = new File(realPath+"/"+fileName);  
			List<JourneyOfLoveActivity> journeyOfLoveActivities = new ArrayList<JourneyOfLoveActivity>();
			JourneyOfLoveActivity  journeyOfLoveActivity = null;
			Organization organization = null;
			Organization cityOrgan = null;
			Organization subCompanyOrgan = null;
			Organization subCityOrgan = null;
			try {   
				FileInputStream is = new FileInputStream(f);  //读取服务器上的文件 
				HSSFWorkbook wbs = new HSSFWorkbook(is);   
				HSSFSheet childSheet = wbs.getSheetAt(0); 
				System.out.println(childSheet.getRow(0).getLastCellNum());
				if(childSheet.getRow(0).getLastCellNum() >= 14){
					
				loop:	for (int j = 1; j <= childSheet.getLastRowNum(); j++) {   
						HSSFRow row = childSheet.getRow(j);   
						journeyOfLoveActivity = new JourneyOfLoveActivity();
						if (null != row) {   
							for (int k = 0; k < 14; k++) {   
								String value = "";
								int number = 0;
								HSSFCell cell = row.getCell((short)k);   
								if (null != cell) {   
									switch (cell.getCellType()) {   
									case HSSFCell.CELL_TYPE_NUMERIC: // 数字   
										System.out.print(cell.getNumericCellValue()   
												+ "   ");
										number = (int)cell.getNumericCellValue();
										value = String.valueOf(cell.getNumericCellValue());
										break;   
									case HSSFCell.CELL_TYPE_STRING: // 字符串   
										System.out.print(cell.getStringCellValue()   
												+ "   "); 
										value = cell.getStringCellValue();
										break;   
									case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean   
										System.out.println(cell.getBooleanCellValue()   
												+ "   ");   
										break;   
									case HSSFCell.CELL_TYPE_FORMULA: // 公式   
										System.out.print(cell.getCellFormula() + "   ");   
										break;   
									case HSSFCell.CELL_TYPE_BLANK: // 空值   
										System.out.println(" ");   
										break;   
									case HSSFCell.CELL_TYPE_ERROR: // 故障   
										System.out.println(" ");   
										break;   
									default:   
										System.out.print("未知类型   ");   
										break;   
									} 
									
								} else {   
									System.out.print("-   ");   
									value="";
								} 
								switch(k){
								case 0:
									 
									journeyOfLoveActivity.setActivityDate(value);
									break;
								case 1:
									organization = organizationService.getOrganizationByFullName(value);
									if (organization != null) {
										if(!"ADMIN".equals(rolename)){
											subCompanyOrgan = (Organization)session.get("barchList");
											if(subCompanyOrgan.getUm_organ_id().equals(organization.getUm_organ_id())){
												journeyOfLoveActivity.setSubCompany(organization.getUm_organ_id());
												journeyOfLoveActivity.setSubComName(value);
											}else{
												errorNumbers.add(j);
												impDataInfor.setFailResaon("4");
												continue loop;
										    }
										}
										if("ADMIN".equals(rolename)){
											journeyOfLoveActivity.setSubCompany(organization.getUm_organ_id());
											journeyOfLoveActivity.setSubComName(value);
										}
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("1");
										continue loop;
									}
								case 2:
									cityOrgan = organizationService.getOrganizationByFullName(value);
									if(cityOrgan!=null){
										if("THIRDADMIN".equals(rolename)){
											subCityOrgan = (Organization)session.get("expensedList");
											if(subCityOrgan.getUm_organ_id().equals(cityOrgan.getUm_organ_id())){
												journeyOfLoveActivity.setSubCity(cityOrgan.getUm_organ_id());
												journeyOfLoveActivity.setSubCityName(value);
											}else{
												errorNumbers.add(j);
												impDataInfor.setFailResaon("4");
												continue loop;
											}
										}
										List<Organization> organList = organizationService.findOrganizationByParentId(organization.getUm_organ_id());
										boolean flag  = false;
										if(!"THIRDADMIN".equals(rolename)){
											for(Organization or : organList){
												if(or.getUm_organ_id().equals(cityOrgan.getUm_organ_id())){
													journeyOfLoveActivity.setSubCity(cityOrgan.getUm_organ_id());
													journeyOfLoveActivity.setSubCityName(value);
													flag = true;
												}
											}
											if(!flag){
												errorNumbers.add(j);
												impDataInfor.setFailResaon("5");
												continue loop;
											}
										}
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("2");
										continue loop;
									}
								case 3:
									journeyOfLoveActivity.setSchool(value);
									break;
								case 4:
									journeyOfLoveActivity.setDonateStuNum(0);
									break;
								case 5:
									if(value!=null && value.length()!=0){
										journeyOfLoveActivity.setDonateMoney(Double.parseDouble(value));
									}else{
										journeyOfLoveActivity.setDonateMoney(0.00);
									}
									break;
								case 6:
									journeyOfLoveActivity.setGreenCardMember(0);
									break;
								case 7:
									journeyOfLoveActivity.setSilverCardMember(0);
									break;
								case 8:
									journeyOfLoveActivity.setGoldenCardMember(0);
									break;
								case 9:
									journeyOfLoveActivity.setPlatinumCardMember(0);
									break;
								case 10:
									journeyOfLoveActivity.setDiamondCardMember(0);
									break;
								case 11:
									journeyOfLoveActivity.setSelfDrivings(number);
									break;
								case 12:
									journeyOfLoveActivity.setActivityFee((double)number);
									break;
								case 13:
									if(value != null && value.length() > 0 ){
										journeyOfLoveActivity.setOaSph(value);
										break;
									}else{
										errorNumbers.add(j);
										impDataInfor.setFailResaon("13");
										continue loop;
									}
								default:  
									break;
								}
							}   
						}
						journeyOfLoveActivity.setCreateDate(new Date()); 
						journeyOfLoveActivity.setUser(user);
						journeyOfLoveActivities.add(journeyOfLoveActivity);
					}
					journeyLoveService.addJourneyLoves(journeyOfLoveActivities);//将从文件读取到的数据封装到对象 持久化到数据库
					impDataInfor.setTotalNum(childSheet.getLastRowNum());
					impDataInfor.setSucceedNum(childSheet.getLastRowNum() - errorNumbers.size());
					impDataInfor.setFailNum(errorNumbers.size());
					String errorDetail = "";
					if(errorNumbers.size()!=0){
						for(Integer num : errorNumbers){
							errorDetail = errorDetail+num+" ";
						}
					}
					impDataInfor.setFailDetail(errorDetail);
				}else{
					impDataInfor.setTotalNum(0);
					impDataInfor.setSucceedNum(0);
					impDataInfor.setFailNum(0);
					impDataInfor.setFailDetail("0");
					impDataInfor.setFailResaon("3");
				}
			} catch (Exception e) {   
				e.printStackTrace();   
			} 
		}
		this.setImpDataInfor(impDataInfor.toString());
        recache();
		return SUCCESS;
	}
	
	
	public String expJourneyLoves(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		User user = (User)session.get(CONSTANT.USER_SESSION_KEY);
		
		String startDate = httpServletRequest.getParameter("startDate");
		String endDate = httpServletRequest.getParameter("endDate");
		String roleName = (String)session.get("rolename");
		JourneyLoveVO journeyLoveVO = new JourneyLoveVO();
		journeyLoveVO.setStartDate(startDate);
		journeyLoveVO.setEndDate(endDate);
		journeyLoveVO.setRoleName(roleName);
		journeyLoveVO.setUser(user);
		if(journeyLove==null){
			journeyLove = new JourneyOfLoveActivity();
		}
		if("SUBADMIN".equals(roleName)){
			 Organization organ = (Organization)session.get("barchList");
			 if(organ!=null){
				 journeyLove.setSubCompany(organ.getUm_organ_id());
			 }
		}else if("THIRDADMIN".equals(roleName)){
			Organization subCompanyOrgan = (Organization)session.get("barchList");
			 if(subCompanyOrgan!=null){
				 journeyLove.setSubCompany(subCompanyOrgan.getUm_organ_id());
			 }
			Organization organ = (Organization)session.get("expensedList");
			 if(organ!=null){
				 journeyLove.setSubCity(organ.getUm_organ_id());
			 }
		} 
		journeyLoveVO.setJourneyOfLoveActivity(journeyLove);
		PagerModel pm = journeyLoveService.getJourneyLoves(journeyLoveVO,curPage);
		String realPath = httpServletRequest.getRealPath("/download/");
		String fileName = "爱心之旅活动信息.xls";
		String[] headers = {"活动日期","分公司","中支","学校","捐助学生人数","捐助金额","绿卡会员人数","银卡会员人数","金卡会员人数","金箔卡会员人数","钻石卡会员人数","自驾车辆数","OA审批号"}; 
		ExpJourneyLoves.exp(headers,journeyLoveService.getJourneyLoves(journeyLoveVO,1,pm.getTotal()==0?1:pm.getTotal()).getDatas(),realPath+"/"+fileName);//将数据读取到服务器上的文件中
	    DownloadExcel.download(realPath,fileName,httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}

	public String expDemo(){
		HttpServletRequest httpServletRequest = ServletActionContext. getRequest();
		HttpServletResponse httpServletResponse = ServletActionContext.getResponse();
		String realPath = httpServletRequest.getRealPath("/download/");
		DownloadDemo.download(realPath,"JourneyLoveDemo.xls;爱心之旅活动模板.xls",httpServletRequest,httpServletResponse);//从服务器上下载文件
		return null;
	}
	public String getMemberType(int dsnum){
		if(dsnum ==0){
			return "绿卡会员";
		}else if(dsnum>=1 && dsnum <= 3){
			return "银卡会员";
		}else if(dsnum>=4 && dsnum<=9){
			return "金卡会员";
		}else if(dsnum>=10 && dsnum<=20){
			return "金箔卡会员";
		}else{
			return "钻石卡会员";
		}
	}
	
}
